# -*- coding: utf-8 -*-
# File : app.py
# Author: taoyahui
# Date : 2022/5/30

#编写服务端接口

from flask import Flask, render_template, request
import sqlite3

app = Flask(__name__)

def execSQL(sql):
    """
    执行sql通用方法
    :param sql:
    :return:
    """
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        result = cursor.fetchall()
        conn.commit()
        return result
    except BaseException as e:
        conn.rollback()
        print('错误: %s' % e)
    finally:
        conn.close()

@app.route('/login', methods=['POST', 'GET'])
def login():
    """
    登录相关功能实现
    :return:
    """
    if request.method == 'POST':
        # 当请求为POST方法时触发
        username = request.form['username']
        password = request.form['password']
        user = execSQL(f"select * from user where username = '{username}'")
        if user[0][1] == password:
            blogs = execSQL("select id, title from blogs")
            return render_template('blog_list.html', blogs=blogs)
        else:
            return render_template('login.html', msg='账户或密码错误')
    else:
        # 如果请求不是POST的话触发
        return render_template('login.html')


# @app.route('/')
# def index():
#     """
#     显示博客列表
#     :return:
#     """
#     blogs = execSQL("select id, title from blogs")
#     return render_template('blog_list.html', blogs= blogs)


@app.route("/blog/<blog_id>")
def blog(blog_id):
    """
    显示具体博客内容
    :param blog_id:
    :return:
    """
    blog = execSQL(f"select * from blogs where id = {blog_id}")
    if blog:
        return render_template("blog.html", blog=blog[0])
    return "<a href='/'>博客未找到！点击回到目录</a>"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)